package com.gdougms.controller;


import com.gdougms.entity.Announcement;
import com.gdougms.entity.HttpMessage;
import com.gdougms.entity.User;
import com.gdougms.mapper.AnnouncementMapper;
import com.gdougms.service.AnnouncementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@Api(value = "体育馆管理系统公告接口" ,tags = {"体育馆管理系统公告接口"})
public class AnnouncementController {
    @Autowired
    AnnouncementService announcementService;

    @Autowired
    ObjectFactory<HttpMessage> httpMessageObjectFactory;

    @Autowired
    HttpSession httpSession;

    @ApiOperation(value = "管理员发布公告",notes = "fileUrl为文件链接，暂时不传也行")
    @PostMapping("/pubAnnouncement")
    public HttpMessage pubAnnounce(@RequestParam String title,
                                   @RequestParam String content,
                                   @RequestParam(required = false) String fileUrl){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        User user = (User)httpSession.getAttribute("User");
        int id = user.getId();

        int result = announcementService.addAnnouncement(title,content,fileUrl,id);

        if(result == 0){
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常，公告发布失败");
            httpMessage.setResult(false);
        }else{
            httpMessage.setCode(200);
            httpMessage.setMessage("公告发布成功");
            httpMessage.setResult(true);
        }

        return httpMessage;
    }

    @ApiOperation(value = "获取全部公告",notes = "object中有length，还有data是公告数据")
    @GetMapping("/announcementList")
    public HttpMessage getall(){
        HttpMessage httpMessage = httpMessageObjectFactory.getObject();
        List<Announcement> announcements = announcementService.announcementList();
        if (announcements != null && announcements.size() > 0){
            httpMessage.setCode(200);
            httpMessage.setMessage("获取公告成功");
            httpMessage.setResult(true);
            Map<String,Object> map = new HashMap<>();
            map.put("length",announcements.size());
            map.put("data",announcements);
            httpMessage.setObject(map);
        }else {
            httpMessage.setCode(-1);
            httpMessage.setMessage("系统异常,获取公告失败");
            httpMessage.setResult(false);
        }
        log.info(announcements.toString());
        return httpMessage;
    }
}
